package com.htjx.mall.admin.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.htjx.mall.admin.controllers.vo.UserQuery;
import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.utils.page.Page;
import com.htjx.mall.services.UserService;

@Controller
@RequestMapping("/admin/user")
public class _UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private ShaPasswordEncoder passwordEncoder;

	/****
	 * 分页查询用户
	 * @param UserQuery
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(UserQuery userQuery, Model model) {
		Page<User> page = new Page<User>();
		page.setPageSize(userQuery.getPageSize());
		page.setPageNo(userQuery.getPageNo());
		page = userService.page(userQuery, page);
		
		model.addAttribute("page", page);
		return "user/list";
	}
	
	@RequestMapping(value = "/detail/{user_id}", method = RequestMethod.GET)
	public String categoryDetail(@PathVariable("user_id") long id, Model model) {
		User user = userService.findUniqueBy("id", String.valueOf(id));
		Result result = null;
		if(user == null) {
			result = new Result(9,"查询用户失败");
		} 
		
		model.addAttribute("result", result);
		model.addAttribute("user", user);
		return "user/detail";
	}
	
	@RequestMapping(value="/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") long id, Model model) {
		User user = userService.findUniqueBy("id", String.valueOf(id));
		model.addAttribute("user", user);
		return "user/update";
	}
	
	@RequestMapping(value="/update", method = RequestMethod.POST)
	public String update(User user, Model model) {
		User ref = userService.findUniqueBy("id", String.valueOf(user.getId()));
		if(ref == null) {
			Result result = new Result(9, "数据有误");
			model.addAttribute("result", result);
			return "redirect:/admin/user/detail/"+user.getId();
		}
		
		String encodePassword = passwordEncoder.encodePassword(user.getPassword(), null);
		ref.setPassword(encodePassword);
		
		userService.updateOne(ref);
		return "redirect:/admin/user/list";
	}
	
}
